<template>
  <x-page>
    <x-filter @search="handleSearch" @reset="resetSearch">
      <x-filter-item :label="$t('orderSynergy.purchase.purchaseNumber')">
        <el-input v-model="searchParams.number" :placeholder="'请输入'" clearable maxlength="50"></el-input>
      </x-filter-item>
      <x-filter-item :label="$t('orderSynergy.purchase.orderState')">
        <x-select
          :placeholder="$t('common.all')"
          v-model="searchParams.state"
          :options="dictOptions['srm_purchase_order.state']"
          style="width: 100%"
        ></x-select>
      </x-filter-item>
      <x-filter-item :label="$t('orderSynergy.purchase.createTime')">
        <el-date-picker
          v-model="searchParams.createTime"
          type="daterange"
          value-format="yyyy-MM-dd"
          :range-separator="$t('common.to')"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          clearable
        >
        </el-date-picker>
      </x-filter-item>
    </x-filter>
    <x-data>
      <template #tool>
        <el-row type="flex" class="tools" justify="space-between">
          <el-col :span="24" class="tools-config">
            <x-column-config :columns="columns" @updateColumns="updateColumns" @on-refresh="loadData" />
          </el-col>
        </el-row>
      </template>
      <x-table
        ref="tableCom"
        :pagination="pagination"
        :data-source="tableData"
        :loading="loading"
        :row-key="'id'"
        @on-change="handleTableChange"
        @on-selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column :label="$t('common.serialNumber')" :width="55" fixed type="index" />
        <el-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :prop="item.prop"
          :fixed="item.fixed"
          :show-overflow-tooltip="true"
          :width="item.width"
          :min-width="item.minWidth || '-'"
          :label="item.label"
          :sortable="'custom'"
        >
          <template #default="scope">
            <span v-if="item.prop === 'state'">{{
              selectDictLabel(dictOptions['srm_purchase_order.state'], scope.row[item.prop])
            }}</span>
             <span v-else-if="item.prop === 'orderType'">{{
              selectDictLabel(dictOptions['srm_purchase_order.order_type'], scope.row[item.prop]) | emptyVal
            }}</span>
            <span v-else>
              {{ scope.row[item.prop] | emptyVal }}
            </span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('common.opeartion')" :align="'center'" width="160">
          <template #default="scope">
            <more-table-actions
              :action-list="getActions(actions, scope.row)"
              :permis-list="permissionsActions"
              :row="scope.row"
              @onActionClick="handleActions"
            />
          </template>
        </el-table-column>
      </x-table>
    </x-data>
  </x-page>
</template>
<script>
import { buttonIcons, PermissionsMixin, QueryDictMixin, TableListMixin, selectDictLabel } from '@package/utils'
import { columns, actions } from '../config/purchaseOrder.js'
import { listUrl, apiPutPurchaseOrderConfirm, apiPutPurchaseOrderRefuse } from '../api/purchaseOrder.js'
import { EnumApiCode } from '../../../../../../globalEnum.js'

export default {
  name: 'PurchaseOrder',
  components: {},
  mixins: [TableListMixin, QueryDictMixin, PermissionsMixin],
  data() {
    return {
      columns,
      actions,
      listUrl,
      loading: false,
      searchParams: {
        number: '',
        supplierName: '',
        state: '',
        createTime: ''
      },
      srmDictKeys: ['srm_purchase_order.state', 'srm_purchase.type', 'srm_purchase_order.order_type']
    }
  },
  computed: {
    getActions() {
      return (actions, row) => {
        const { state } = row
        // 需要判断是不是非发起人 非发起人只有查看
        return actions.map((action) => {
          const { key } = action
          switch (state) {
            case 1: // 待确认
              action.disabled = !['detail', 'confirm', 'refuse'].includes(key)
              break
            default:
              action.disabled = !['detail'].includes(key)
              break
          }

          return action
        })
      }
    }
  },
  mounted() {},
  methods: {
    buttonIcons,
    selectDictLabel,
    handleSearch(val) {
      const { supplierName, number, state, createTime } = this.searchParams
      this.queryParam = {
        ...val,
        supplierName,
        number,
        state,
        beginTime: createTime ? `${createTime[0]} 00:00:00` : '',
        endTime: createTime ? `${createTime[1]} 23:59:59` : ''
      }
      this.loadData()
    },
    handleChangeSupplier(val) {
      this.searchParams.supplierName = val.supplierName
    },
    handleActions({ key, data }) {
      const { id } = data
      switch (key) {
        case 'detail':
          this.$router.push({
            name: 'PurchaseOrderDetail',
            query: {
              id
            }
          })
          break
        case 'confirm':
          // this.$confirm('是否确认采购订单?', '提示', {
          //   confirmButtonText: '确定',
          //   cancelButtonText: '取消',
          //   type: 'warning'
          // })
          //   .then((confirm) => {
          //     this.handlePurchaseOrderConfirm(id)
          //   })
          //   .catch((cancel) => {})
          this.$router.push({
            name: 'PurchaseOrderDetail',
            query: {
              id
            }
          })
          break
        case 'refuse':
          this.$confirm('是否拒绝采购订单?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then((confirm) => {
              this.handlePurchaseOrderRefuse(id)
            })
            .catch((cancel) => {})
          break
      }
    },
    // 确认
    async handlePurchaseOrderConfirm(id) {
      const { code, msg } = await apiPutPurchaseOrderConfirm(id)
      if (code === EnumApiCode.Success) {
        this.$message.success('确认成功')
        this.loadData()
      } else {
        this.$message.error(msg)
      }
    },
    // 拒绝
    async handlePurchaseOrderRefuse(id) {
      const { code, msg } = await apiPutPurchaseOrderRefuse(id)
      if (code === EnumApiCode.Success) {
        this.$message.success('拒绝成功')
        this.loadData()
      } else {
        this.$message.error(msg)
      }
    }
  }
}
</script>
